package team.bluepen.order.web.servlet.order;

import space.lingu.light.LightRuntimeException;
import team.bluepen.order.ErrorPack;
import team.bluepen.order.constant.ErrorCode;
import team.bluepen.order.data.database.hive.OrderRepository;
import team.bluepen.order.util.Log;
import team.bluepen.order.util.StringUtil;
import team.bluepen.order.web.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 文件导入
 * @author RollW
 */
@WebServlet(name = "OrderFileServlet", urlPatterns = "/api/order/file")
public class OrderFileServlet extends BaseServlet {
    public static final String PATH_PARAM = "path";

    @Override
    protected void post(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getParameter(PATH_PARAM);
        setJsonHeader(resp);
        if (StringUtil.isEmpty(path)) {
            writeJson(resp, new ErrorPack(ErrorCode.ERROR_PARAM_MISSING,
                    "Missing path param.").toCodePack());
            return;
        }
        OrderRepository repository = new OrderRepository();
        // 只允许Hdfs文件导入
        try {
            repository.getOrderDao().loadData(path, false);
        } catch (LightRuntimeException e) {
            writeJson(resp, new ErrorPack(ErrorCode.ERROR_DATABASE,
                    e.getMessage()).toCodePack());
            Log.e("OrderImport", e);
            return;
        }

        writeJson(resp, new ErrorPack(ErrorCode.SUCCESS,
                "SUCCESS").toCodePack());
    }
}
